//
//  YWTakePhotoAndVideoController.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/9/21.
//

#import "YWTakePhotoAndVideoController.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "YWProgressView.h"

#import "YWVideoController.h"
#import "YWVideoController.h"

#import <CoreMotion/CoreMotion.h>


#define MaxTime 10

@interface YWTakePhotoAndVideoController ()<YWProgressViewDelegate,AVCapturePhotoCaptureDelegate,AVCaptureFileOutputRecordingDelegate>

@property (weak, nonatomic) IBOutlet UIView *bgView;

@property(nonatomic,weak)UIButton *toggleCameraBtn;

@property (weak, nonatomic) IBOutlet YWProgressView *progressView;


@property(nonatomic,assign)CGFloat currentTime;

@property (nonatomic,strong)NSTimer *timer;



@property(nonatomic,strong) AVCaptureDevice *device;//捕获设备，前置摄像头，后置摄像头（音频输入）
@property(nonatomic,strong) AVCaptureDevice *audioDevice;//捕获设备，麦克风（音频输入）

@property (strong,nonatomic) AVCaptureDeviceInput *input;//录像画面输入流
@property (strong,nonatomic) AVCaptureDeviceInput *audioInput;//声音输入流

@property (nonatomic,strong) AVCapturePhotoOutput *photoOutput;//照片输出流
@property (strong,nonatomic) AVCaptureMovieFileOutput *captureMovieFileOutput;//视频输出流

@property (strong,nonatomic) AVCaptureSession *session;//负责输入和输出设置之间的数据传递
@property (strong,nonatomic) AVCaptureVideoPreviewLayer *previewLayer;//相机拍摄预览图层

@property(nonatomic,strong)UIImage *saveImage;

@property(nonatomic,strong)NSURL *preVideoURL; //获取存储路径 存储路径在沙盒中，需要唯一




// 陀螺仪,检测屏幕方向
@property (nonatomic, strong) CMMotionManager * motionManager;
@property (nonatomic, assign) UIDeviceOrientation deviceOrientation; //保存通过陀螺仪知道的当前手机方向、因为苹果手机可以设置永远不旋转屏幕这样就监测不了方向、所以要使用陀螺仪认为地制造并保存手机方向

@end

@implementation YWTakePhotoAndVideoController


- (void)startMotionManager{
    if (_motionManager == nil) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    else{
        return;  //假如陀螺仪已经存在就返回不走下面的了、避免重复操作
    }
    _motionManager.deviceMotionUpdateInterval = 1/15.0;
    if (_motionManager.deviceMotionAvailable) {
        NSLog(@"Device Motion Available");
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler: ^(CMDeviceMotion *motion, NSError *error){
            
            [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
            
        }];
    } else {
        NSLog(@"No device motion on device.");
        [self setMotionManager:nil];
    }
}

- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x))
    {
        if (y >= 0){
            self.deviceOrientation = UIDeviceOrientationPortraitUpsideDown;
        }
        else{
            self.deviceOrientation = UIDeviceOrientationPortrait;
        }
    }
    else
    {
        if (x >= 0){
            self.deviceOrientation = UIDeviceOrientationLandscapeRight;
        }
        else{
            self.deviceOrientation = UIDeviceOrientationLandscapeLeft;
        }
    }
    
    YWLog(@"orientation:%ld",self.deviceOrientation);
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    // 开启陀螺仪
    [self startMotionManager];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [_motionManager stopDeviceMotionUpdates];
    _motionManager = nil;
}


-(void)handleVideoOrientationWithIsVideo:(BOOL)isVideo{
    
    //设置拍视频方向
    AVCaptureConnection *captureConnection = nil;
    if(isVideo == YES){
        
        captureConnection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    }else{
        
        captureConnection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
    }
    
    
    //写在开始拍摄的时候就确定视频拍摄方向、而不是写在output的get方法那里
    if (!captureConnection.supportsVideoOrientation) {
        return;
    }
    
    switch (self.deviceOrientation) {
        case UIDeviceOrientationUnknown:
        case UIDeviceOrientationPortrait:
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
            }
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            }
            break;
        case UIDeviceOrientationLandscapeLeft:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
            }
            break;
        case UIDeviceOrientationLandscapeRight:
            {
                captureConnection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
            }
            break;
       
        default:
            break;
    }
    
    
    //不要用手机的方向了、因为苹果手机可以设置永远不旋转屏幕这样就监测不了方向、所以要使用陀螺仪的方向
//    NSInteger deviceOrientation = [UIDevice currentDevice].orientation;
//    YWLog(@"capture orientation:%ld",deviceOrientation);

    //不需要区分前后摄像头了
//    if(self.input.device.position == AVCaptureDevicePositionFront) {//处理前置摄像头拍摄
//    }
//    else{ //后摄像头处理
//    }
    
}







-(AVCaptureDevice *)device{
    if(_device == nil){
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        _device = device;
        
    }
    return _device;
}

-(AVCaptureDevice *)audioDevice{
    if(_audioDevice == nil){
        AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
        _audioDevice = audioDevice;
    }
    return _audioDevice;
}


-(AVCaptureDeviceInput *)input{
    if(_input == nil){
        NSError *error = nil;
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
        _input = input;
        
    }
    return _input;
}

-(AVCaptureDeviceInput *)audioInput{
    if(_audioInput == nil){
        NSError *error = nil;
        AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:self.audioDevice error:&error];
        _audioInput = audioInput;
        
    }
    return _audioInput;
}

-(AVCapturePhotoOutput *)photoOutput{
    if(_photoOutput == nil){
        AVCapturePhotoOutput *photoOutput = [[AVCapturePhotoOutput alloc]init];
        _photoOutput = photoOutput;
    }
    return _photoOutput;
}

-(AVCaptureMovieFileOutput *)captureMovieFileOutput{
    if(_captureMovieFileOutput == nil){
        AVCaptureMovieFileOutput *captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc]init];
        AVCaptureConnection *captureConnection = [_captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
        //这是防抖功能
        if ([captureConnection isVideoStabilizationSupported ]) {
            captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
            
        }
        _captureMovieFileOutput = captureMovieFileOutput;
        
    }
    return _captureMovieFileOutput;
}


-(AVCaptureSession *)session{
    if(_session == nil){
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        _session = session;
        //拿到的图像的大小可以自行设定
        if ([session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
            [session setSessionPreset:AVCaptureSessionPreset1280x720];
        }
    }
    return _session;
}

-(AVCaptureVideoPreviewLayer *)previewLayer{
    if(_previewLayer == nil){
        AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait; // 图层展示拍摄角度方向
        _previewLayer = previewLayer;
        
    }
    return _previewLayer;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setBackgroundImage:[UIImage imageNamed:@"摄像头反转"] forState:UIControlStateNormal];
    btn.size = CGSizeMake(30, 30);
    [btn addTarget:self action:@selector(toggleCamera) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.toggleCameraBtn = btn;
    
    self.progressView.delegate = self;
    
    
    //准备拍照
    [self prepareTakePhotoAuthorization];
    
    //开始扫描
    [self startScan];
    
    
}



-(void)cancelClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//切换摄像头
- (void)toggleCamera{
   
    [UIView transitionWithView:self.bgView duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
        
            AVCaptureDevicePosition position = self.input.device.position;
               AVCaptureDevice *newVideoDevice = nil;
               if (position == AVCaptureDevicePositionBack) {
                   newVideoDevice = [self videoDeviceWithPosition:AVCaptureDevicePositionFront];
               } else {
                   newVideoDevice = [self videoDeviceWithPosition:AVCaptureDevicePositionBack];
               }
               NSError *error;
               AVCaptureDeviceInput *newVideoInput = [AVCaptureDeviceInput deviceInputWithDevice:newVideoDevice error:&error];
               if (error) {
                   // 错误处理
                   return;
               }
               [self.session beginConfiguration];
               [self.session removeInput:self.input];
               if ([self.session canAddInput:newVideoInput]) {
                   [self.session addInput:newVideoInput];
                   self.device = newVideoDevice;
                   self.input = newVideoInput;
               } else {
                   [self.session addInput:self.input];
               }
               [self.session commitConfiguration];
            
    } completion:^(BOOL finished) {

    }];
    
}


-(void)progressViewDidTap:(YWProgressView *)progressView{
    
    YWLog(@"1- progressViewDidTap");
    
    [self takePhoto];
    
}

-(void)progressViewDidStartLongPress:(YWProgressView *)progressView{
    
    YWLog(@"1- progressViewDidStartLongPress");
    
    [self startTakeVideo];
    
}

-(void)progressViewDidEndLongPress:(YWProgressView *)progressView{
    
    YWLog(@"1- progressViewDidEndLongPress");

    [self endTakeVideo];
}


//添加定时器
-(void)addTimer{
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addCurrentTime) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

//移除定时器
-(void)removeTimer{
    
    [self.timer invalidate];
    
    self.timer = nil;
    
}

-(void)addCurrentTime{
    
    self.currentTime += 0.01;
    
    self.progressView.progressValue = self.currentTime/MaxTime;
    
    if(self.currentTime >= MaxTime){
        [self endTakeVideo];
    }
    
}



//开启拍照权限
-(void)prepareTakePhotoAuthorization{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if(authStatus != AVAuthorizationStatusAuthorized){
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        if (granted) {
                           // 申请权限成功
                        } else {
                            // 申请权限失败
                        }
                    });
        }];
    }
}


-(void)startScan{
    
    if([self.session canAddInput:self.input] && [self.session canAddInput:self.audioInput] && [self.session canAddOutput:self.photoOutput] && [self.session canAddOutput:self.captureMovieFileOutput]) {//不是所有的输入输出都能添加进来所以要判断
        
        //会话添加输入输出
        [self.session addInput:self.input];
        [self.session addInput:self.audioInput];
        [self.session addOutput:self.photoOutput];
        [self.session addOutput:self.captureMovieFileOutput];
    }
    else{
        return;
    }
    
    [self.bgView.layer addSublayer:self.previewLayer];
    
    [self.session startRunning];
    
}


- (void)dealloc{
    [self.session stopRunning];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.previewLayer.frame = self.bgView.bounds;
}


-(void)takePhoto{
        
        [UIView animateWithDuration:0.1 animations:^{
            self.bgView.alpha = 0;
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 animations:^{
                self.bgView.alpha = 1;
            }];
        }];
        
        //确定拍摄方向
        [self handleVideoOrientationWithIsVideo:NO];
        
        AVCapturePhotoSettings *set = [AVCapturePhotoSettings photoSettings];
        
        [self.photoOutput capturePhotoWithSettings:set delegate:self];

}


//开始录制
-(void)startTakeVideo{
    
    [UIView animateWithDuration:0.3 animations:^{
        self.progressView.transform = CGAffineTransformMakeScale(1.25, 1.25);
    }];
    
    self.toggleCameraBtn.hidden = YES;
    
    if (self.timer == nil) { //定时器不存在才去加载
        //添加定时器
        [self addTimer];
        
    }
    
    //处理拍视频的方向
    [self handleVideoOrientationWithIsVideo:YES];
    
    //获取存储路径 存储路径在沙盒中，需要唯一
    self.preVideoURL = [self createVideoFilePathUrl];
    
    //调用录制方法传入路径，文件自动写入 直接调用录制方法，不需要配置文件写入对象
    [self.captureMovieFileOutput startRecordingToOutputFileURL:self.preVideoURL recordingDelegate:self];

    
}

//结束录制
-(void)endTakeVideo{
    
    [self removeTimer];
    
    self.currentTime = 0;
    
    [self.progressView clearProgress];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.progressView.transform = CGAffineTransformIdentity;
    }];
    
    self.toggleCameraBtn.hidden = NO;
    
    //完成录制
    [self.captureMovieFileOutput stopRecording];
    
    
    //跳去下一个VC那里播放
    YWVideoController *vc = [[YWVideoController alloc] initWithNibName:@"YWVideoController" bundle:nil];
    
    vc.saveVideoUrl = self.preVideoURL;
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
//接下来是将视频本地URL转为NSData并像上传图片那样做法上传视频到后台、可以参考华人发布那里做法、这里没接口暂时先不做
    
}


#pragma mark - 私有方法/***  取得指定位置的摄像头**  @param position 摄像头位置**  @return 摄像头设备*/
- (AVCaptureDevice *)videoDeviceWithPosition:(AVCaptureDevicePosition)position {
    AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
    NSArray *devices = discoverySession.devices;
    for (AVCaptureDevice *device in devices) {
        if (device.position == position) {
            return device;
        }
    }
    return nil;
}


//生成路径
- (NSURL *)createVideoFilePathUrl
{
    NSString *documentPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/shortVideo"];
    
//    NSString *documentPath = YWVideoSavepath;

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];

    NSString *destDateString = [dateFormatter stringFromDate:[NSDate date]];
    NSString *videoName = [destDateString stringByAppendingString:@".mp4"];

    NSString *filePath = [documentPath stringByAppendingFormat:@"/%@",videoName];

    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isDir;
    if (![manager fileExistsAtPath:documentPath isDirectory:&isDir]) {
        [manager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];

    }
    
    return [NSURL fileURLWithPath:filePath];
}

//录像代理方法
//AVCaptureMovieFileOutput方式提供了暂停录制方法和恢复录制方法，但是仅mac os可用
- (void)captureOutput:(AVCaptureFileOutput *)output didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections{
    
}

- (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(nullable NSError *)error{
    
    if(error != nil){
        [self removeTimer];
        
        self.currentTime = 0;
        
        [self.progressView clearProgress];
        
        [UIView animateWithDuration:0.3 animations:^{
            self.progressView.transform = CGAffineTransformIdentity;
        }];
        
        self.toggleCameraBtn.hidden = NO;
        
    }
    
    //无论error是否等于nil都保存到相册（因为你把app退到后台它也走error）
    
    //判断是否授权保存到相册
    [self judgeIsAuthorizedForVideo];

}



//判断是否授权保存到相册
-(void)judgeIsAuthorizedForVideo{
      // 1.获取用户授权状态,状态有四种
        // 1) PHAuthorizationStatusNotDetermined  不确定
        // 2)  PHAuthorizationStatusRestricted, 家长控制,拒绝
        // 3)  PHAuthorizationStatusDenied, 拒绝
        // 4) PHAuthorizationStatusAuthorized 授权
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
     // 2.判断用户的授权状态
        if (status == PHAuthorizationStatusNotDetermined) {
                // 如果状态是不确定的话,block中的内容会等到授权完成再调用
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                // 授权完成就会调用
                if (status == PHAuthorizationStatusAuthorized) {
                //调用存储图片的方法
                    [self saveVideo];
                }
            }];
            //如果允许访问
        } else if (status == PHAuthorizationStatusAuthorized) {
            //调用存储图片的方法
            [self saveVideo];
            //如果权限是拒绝
        } else {
            // 使用第三方框架,弹出一个页面提示用户去打开授权
           // [SVProgressHUD showInfoWithStatus:@"进入设置界面->找到当前应用->打开允许访问相册开关"];
        }
    
}


-(void)saveVideo{
    
    //录制完成之后可以通过之前的路径来获取视频文件，进行播放、保存等操作
    
    //修改系统相册用PHPhotoLibrary单例,调用performChanges,否则苹果会报错,并提醒你使用
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        // 调用判断是否已有该名称相册
       PHAssetCollection *assetCollection = [self fetchAssetColletion:
    @"YWPhotoEditMaster"];
        //创建一个操作图库的对象
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest;
        
        if (assetCollection) {
            // 已有相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        } else {
            // 1.创建自定义相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"YWPhotoEditMaster"];
        }
        
        // 2.保存你需要保存的图片到系统相册(这里保存的是self.saveImage的图片)
//        PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:self.saveImage];
        
        PHAssetChangeRequest *assetChangeRequest =  [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:self.preVideoURL];
        
        // 3.把创建好图片添加到自己相册
        //这里使用了占位图片,为什么使用占位图片呢
        //这个block是异步执行的,使用占位图片先为图片分配一个内存,等到有图片的时候,再对内存进行赋值
        PHObjectPlaceholder *placeholder = [assetChangeRequest placeholderForCreatedAsset];
        [assetCollectionChangeRequest addAssets:@[placeholder]];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        //弹出一个界面提醒用户是否保存成功
        if (error) {
            //[SVProgressHUD showErrorWithStatus:@"保存失败"];
        } else {
           // [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        }
        
        
    }];
    
}

//该方法获取在图库中是否已经创建该App的相册
//该方法的作用,获取系统中所有的相册,进行遍历,若是已有相册,返回该相册,若是没有返回nil,参数为需要创建  的相册名称
-(PHAssetCollection *)fetchAssetColletion:(NSString *)albumTitle{
    // 获取所有的相册
    PHFetchResult *result = [PHAssetCollection           fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    //遍历相册数组,是否已创建该相册
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle isEqualToString:albumTitle]) {
            return assetCollection;
        }
    }
    return nil;
}


//照片代理
-(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error {
    if (!error) {
        NSData *imageData = [photo fileDataRepresentation];
        UIImage *image = [UIImage imageWithData:imageData];
        
        YWLog(@"dd - 拍照成功")
        
        self.saveImage = image;
        
        //在市场上主流App中,大多数App都具有存储图片到自己App的相册中
        //判断是否授权保存到相册
        [self judgeIsAuthorizedForPhoto];
        
    }
    
}


//判断是否授权保存到相册
-(void)judgeIsAuthorizedForPhoto{
    
      // 1.获取用户授权状态,状态有四种
        // 1) PHAuthorizationStatusNotDetermined  不确定
        // 2)  PHAuthorizationStatusRestricted, 家长控制,拒绝
        // 3)  PHAuthorizationStatusDenied, 拒绝
        // 4) PHAuthorizationStatusAuthorized 授权
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
     // 2.判断用户的授权状态
        if (status == PHAuthorizationStatusNotDetermined) {
                // 如果状态是不确定的话,block中的内容会等到授权完成再调用
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                // 授权完成就会调用
                if (status == PHAuthorizationStatusAuthorized) {
                //调用存储图片的方法
                    [self savePhoto];
                }
            }];
            //如果允许访问
        } else if (status == PHAuthorizationStatusAuthorized) {
            //调用存储图片的方法
            [self savePhoto];
            //如果权限是拒绝
        } else {
            // 使用第三方框架,弹出一个页面提示用户去打开授权
           // [SVProgressHUD showInfoWithStatus:@"进入设置界面->找到当前应用->打开允许访问相册开关"];
        }
    
}

//保存图片的方法
-(void)savePhoto{
   //修改系统相册用PHPhotoLibrary单例,调用performChanges,否则苹果会报错,并提醒你使用
   [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
       
       // 调用判断是否已有该名称相册
      PHAssetCollection *assetCollection = [self fetchAssetColletion:
   @"YWPhotoEditMaster"];
       //创建一个操作图库的对象
       PHAssetCollectionChangeRequest *assetCollectionChangeRequest;
       
       if (assetCollection) {
           // 已有相册
           assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
       } else {
           // 1.创建自定义相册
           assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"YWPhotoEditMaster"];
       }
       
       // 2.保存你需要保存的图片到系统相册(这里保存的是self.saveImage的图片)
       PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:self.saveImage];
       
       // 3.把创建好图片添加到自己相册
       //这里使用了占位图片,为什么使用占位图片呢
       //这个block是异步执行的,使用占位图片先为图片分配一个内存,等到有图片的时候,再对内存进行赋值
       PHObjectPlaceholder *placeholder = [assetChangeRequest placeholderForCreatedAsset];
       [assetCollectionChangeRequest addAssets:@[placeholder]];
       
   } completionHandler:^(BOOL success, NSError * _Nullable error) {
       //弹出一个界面提醒用户是否保存成功
       if (error) {
           //[SVProgressHUD showErrorWithStatus:@"保存失败"];
       } else {
          // [SVProgressHUD showSuccessWithStatus:@"保存成功"];
       }
       
       
   }];
}




@end
